﻿using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using Cimbalino.Phone.Toolkit.Services;
using DepSoft.Mobile.WP8.FollwIt.Framework;
using DepSoft.Mobile.WP8.FollwIt.Framework.Interfaces;
using DepSoft.Mobile.WP8.FollwIt.Model;
using FollwItPortable;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Practices.ServiceLocation;

namespace DepSoft.Mobile.WP8.FollwIt.ViewModel
{
    public class FollwItViewModel : AppCreativityViewModelBase
    {
        private ISecurityService _securityService;
        private IFollwItClient _follwItClient;

        private string _userName;
        public string UserName
        {
            get { return _userName; }
            set
            {
                if (_userName == value)
                    return;

                _userName = value;
                RaisePropertyChanged();
            }
        }

        private string _password;
        public string Password
        {
            get { return _password; }
            set
            {
                if (_password == value)
                    return;

                _password = value;
                RaisePropertyChanged();
            }
        }

        private bool _loginFailed = false;        
        public bool LoginFailed
        {
            get { return _loginFailed; }
            set
            {
                if (_loginFailed == value)
                    return;

                _loginFailed = value;
                RaisePropertyChanged();
            }
        }

        private Security _security;
        public Security Security
        {
            get { return _security; }
            set
            {
                if (_security == value)
                    return;

                _security = value;
                RaisePropertyChanged();
            }
        }

        public RelayCommand AuthenticateCommand { get; private set; }
        public RelayCommand DisconnectCommand { get; private set; }
        public RelayCommand<CancelEventArgs> BackKeyPressCommand { get; private set; }

        public FollwItViewModel(ISecurityService securityService, IFollwItClient follwItClient, INavigationService navigationService, IMessenger messenger)
            : base(navigationService, messenger)
        {
            _securityService = securityService;
            _follwItClient = follwItClient;

#if !DEBUG
            GoogleAnalytics.EasyTracker.GetTracker().SendView("FollwItPage");
#endif

            AuthenticateCommand = new RelayCommand(async () => Authenticate());
            DisconnectCommand = new RelayCommand(async () => Disconnect());
            BackKeyPressCommand = new RelayCommand<CancelEventArgs>(BackKeyPress);

            base.ViewLoadedCommand = new RelayCommand(async () =>
            {
                this.Security = await _securityService.GetCredentialsAsync();

                //Small hack just to be sure we set the authentication flag!
                if(!ReferenceEquals(this.Security, null) && !string.IsNullOrEmpty(this.Security.UserName) && !string.IsNullOrEmpty(this.Security.Password))
                    ServiceLocator.Current.GetInstance<IApplicationSettingsService>().Set("Authenticated", true);

                //Only keep track of the view loaded event once, at program startup
                ViewLoadedCommandEnabled = false;
            });
        }

        private void BackKeyPress(CancelEventArgs e)
        {
            if (!ReferenceEquals(this.Security, null))
            {
                if (!ReferenceEquals(e, null))
                    e.Cancel = true;

                Deployment.Current.Dispatcher.BeginInvoke(() => _navigationService.NavigateTo(Constants.MAINURI));
            }
            else
            {
                while(_navigationService.CanGoBack)
                    _navigationService.RemoveBackEntry();
            }
        }

        private async Task Disconnect()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => this.IsBusy = true);

            this.Security = null;
            ServiceLocator.Current.GetInstance<IApplicationSettingsService>().Set("Authenticated", false);
            await _securityService.ClearCredentialsAsync();

            Deployment.Current.Dispatcher.BeginInvoke(() => this.IsBusy = false);
        }

        private async Task Authenticate()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => this.IsBusy = true);

            bool authenticated = false;
            if (!string.IsNullOrEmpty(this.UserName) && !string.IsNullOrEmpty(this.Password))
                authenticated = await _follwItClient.AuthenticateAsync(this.UserName, this.Password);

            ServiceLocator.Current.GetInstance<IApplicationSettingsService>().Set("Authenticated", authenticated);

            if (authenticated)
            {
                this.Security = new Security() {UserName = this.UserName, Password = this.Password};
                await _securityService.SaveCredentialsAsync(this.Security);

                Deployment.Current.Dispatcher.BeginInvoke(() => this.LoginFailed = false);
                Deployment.Current.Dispatcher.BeginInvoke(() => this.IsBusy = false);
                this.BackKeyPress(null);
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => this.LoginFailed = true);
                Deployment.Current.Dispatcher.BeginInvoke(() => this.IsBusy = false);
            }

        }
    }
}
